#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
    日志
'''

import os, logging, logging.handlers, traceback

__LOG_FILE = './runlog.log'


logger = logging.getLogger(__name__)

def prepareLogdir():
    log_path = os.path.dirname(__LOG_FILE)
    if not os.path.isdir(log_path):
        os.makedirs(log_path)

def configLog():
    prepareLogdir()

    formatter = logging.Formatter("[%(asctime)-11s]: %(module)s %(levelname)s %(message)s")
    handler = logging.handlers.TimedRotatingFileHandler(__LOG_FILE, when='midnight', backupCount=30)
    handler.setFormatter(formatter)

    logging.getLogger('').addHandler(handler)
    logging.getLogger('').setLevel(logging.DEBUG)


def print_debug(logger, msg):
    print "[Debug]:%s\n" % msg
    logger.debug(msg)

def print_info(logger, msg):
    print "[info]:%s\n" % msg
    logger.info(msg)
    
def print_warning(logger, msg):
    print "----------------[warning]:%s\n" % msg
    logger.warning(msg)

def print_error(logger, msg):
    print "****************[Error]:%s\n" % msg
    logger.error(msg)   #错误信息写日志
    try:  
        #把错误信息写到DB
        msg = msg.replace("'", '"')
        msg = msg.replace("\\", '\\\\')
        tmpStrSql = "insert into t_log_error(msg, timeline) values('%s', now())" % msg
        import util
        util.SqlThread.addSqlStr(tmpStrSql) #线程写记录 
    except Exception:
        logger.warning('print_error error:\n%s' % traceback.format_exc())
    

##-----测试-----
#logger = logging.getLogger(__name__)
#configLog()
#
#print_debug(logger, "test debug %s" % ("ssss",))
#print_info(logger, "test info")
#print_warning(logger, "test warning")
#print_error(logger, "test error")
